<template>
  <el-dialog :title="title" :visible="showDialog" :before-close="handleClose" @close="btnCancel">
    <el-form v-if="title === '新增角色'" ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleForm.description" />
      </el-form-item>
    </el-form>
    <el-form v-else ref="roleForm" :model="roleDetail" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleDetail.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleDetail.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
      require: true
    },
    title: {
      type: String,
      default: '',
      require: true
    },
    roleDetail: {
      type: Object,
      default: () => {},
      require: true
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ min: 1, max: 50, message: '角色名称最多1-50个字符', trigger: 'blur' }]
      }
    }
  },
  methods: {
    btnCancel() {
      // 1. 回复表单初始值
      // 2. 清空校验
      // resetFields 方法可以清空所有表单绑定了的数据,还可以清空校验
      this.$refs.roleForm.resetFields() // 重置校验字段
      this.$emit('update:showDialog', false)
    },
    btnOK() {
      // 校验表单
      this.$refs.roleForm.validate(vail => {
        if (vail) {
          if (this.title === '新增角色') {
            this.$emit('sumbit', this.roleForm, vail)
          } else {
            this.$emit('sumbit', this.roleDetail, vail)
          }
        }
      })
    },
    // Dialog的x箭头关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>

</style>
